// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package trace_cmd

import (
	"fmt"
	"strings"
	"time"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/trace_api"
	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/utils"
	"github.com/spf13/cobra"
)

var listTraceCmd_rootSpanName string
var listTraceCmd_pastHour uint32
var listTraceCmd_limit uint32
var listTraceCmd_sortBy uint32

var listTraceCmd = &cobra.Command{
	Use: "listTrace",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 2 {
			return fmt.Errorf("need param [serviceName] [serviceVersion]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.Port.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		serviceName := args[0]
		serviceVersion := args[1]

		client := trace_api.NewTraceApiClient(conn)
		nowTime := time.Now().UnixMilli()
		if listTraceCmd_sortBy > 1 {
			listTraceCmd_sortBy = 1
		}
		res, err := client.ListTrace(cmd.Context(), &trace_api.ListTraceRequest{
			AccessToken: cfg.SuperToken,
			Service: &trace_api.ServiceInfo{
				ServiceName:    serviceName,
				ServiceVersion: serviceVersion,
			},
			FilterByRootSpanName: listTraceCmd_rootSpanName != "",
			RootSpanName:         listTraceCmd_rootSpanName,
			FromTime:             nowTime - int64(listServiceCmd_pastHour)*3600*1000,
			ToTime:               nowTime,
			Limit:                listTraceCmd_limit,
			SortBy:               trace_api.SORT_BY(listTraceCmd_sortBy),
		})
		if err != nil {
			return err
		}
		if res.Code != trace_api.ListTraceResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Println("trace count", len(res.TraceList))
		for _, trace := range res.TraceList {
			fmt.Println("traceId", trace.TraceId)
			fmt.Printf("%s startTime:%s,endTime:%s,consumeTime:%dms\n", trace.RootSpan.SpanName,
				time.UnixMilli(trace.RootSpan.StartTimeStamp).Format(time.DateTime),
				time.UnixMilli(trace.RootSpan.EndTimeStamp).Format(time.DateTime),
				trace.RootSpan.EndTimeStamp-trace.RootSpan.StartTimeStamp,
			)
			attrList := []string{}
			for _, attr := range trace.RootSpan.AttrList {
				attrList = append(attrList, fmt.Sprintf("%s=%s", attr.Key, attr.Value))
			}
			if len(attrList) > 0 {
				fmt.Printf("    attrs:%s\n", strings.Join(attrList, ","))
			}
			fmt.Println("===========================================================")
		}
		return nil
	},
}

func init() {
	listTraceCmd.Flags().StringVar(&listTraceCmd_rootSpanName, "rootSpanName", "", "trace root span name")
	listTraceCmd.Flags().Uint32Var(&listTraceCmd_pastHour, "pastHour", 1, "past hours from now")
	listTraceCmd.Flags().Uint32Var(&listTraceCmd_limit, "limit", 10, "max result count")
	listTraceCmd.Flags().Uint32Var(&listTraceCmd_sortBy, "sortBy", 1, "trace sort order(0 for startTime,1 for consumeTime)")
}
